<template>
    <div class="loan-iou-detail" v-if='pageLoaded'>
        <!-- wrapper -->
        <div class="wrapper">
            <img v-if='type == "share"' src="../images/sharelanding_head.jpg" width="100%">
            <div class="loan-detail-main">
                <div class="loan-detail-number">
                    <p class="loan-detail-number__number">编号: {{ number }}</p>
                    <span class="loan-detail-number__status orange">{{ detail.receiptStateStr }}</span>
                </div>
                <div class="loan-detail-money">
                    <div class="iou-detail-people">
                        <p class='iou-detail-people__item'>出借人： <span>{{detail.lendUserName || placeholder}}</span></p>
                        <p class='iou-detail-people__item'>借款人： <span>{{detail.borrowUserName || placeholder}}</span></p>
                    </div>
                    <ul class="loan-detail-money__list">
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.borrowAmount | toYuan}}元</span>
                            <p>借款总额(元)</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.yearRate/100}}%</span>
                            <p>年利率</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.borrowDays}}</span>
                            <p>借款时长(天)</p>
                        </li>
                    </ul>
                </div>
                <div class="loan-detail-info">
                    <ul class="card__info">
                        <li class="card__info-item">借款日期：{{ detail.borrowTime | dateFormat  }}</li>
                        <li class="card__info-item">还款日期：{{ detail.repayTime | dateFormat }}</li>
                        <li class="card__info-item">生成日期：{{ detail.createdAt | dateFormat }}</li>
                        <li class="card__info-item">借款用途：{{ detail.borrowUsage || placeholder }}</li>
                    </ul>
                </div>
                <div class="loan-detail-agreement"><span class="button short pure" @click='showAgreement = true'>查看借款协议</span></div>
            </div>
            <p class='countdown'> - <span>离还款日还有</span><count-down :date='detail.repayTime'></count-down> - </p>
        </div>
            
        <!-- footer -->
        <footer class="single-button" v-if='!userInfo.user'>
            <span class="button" @click='showLogin = true'>查看详情</span>
        </footer>
        <template v-else>
            <footer class="footer-button"
                v-if='detail.iAmInitiator && (detail.receiptState == "WAIT_CONFIRM" || detail.receiptState == "RETURNED")'>
                <span class="button transparent" @click='show_confirm_delete = true'>删除借条</span>
                <span class="button" @click='showShare'>发送给对方</span>
            </footer>
            <footer class="footer-button" v-if='!detail.iAmInitiator && (detail.iAmBorrower || detail.iAmlender) && (detail.receiptState == "WAIT_CONFIRM" || detail.receiptState == "RETURNED")'>
                <span class="button transparent" @click='show_confirm_return = true'>退回</span>
                <span class="button" @click='setAgreeIOU'>同意借条</span>
            </footer>
            <footer class="single-button" v-if='detail.iAmBorrower && detail.receiptState == "WAIT_PAY"'>
                <span class="button" @click='showShare'>发送给对方</span>
            </footer>
            <footer class="single-button" v-if='detail.iAmlender && detail.receiptState == "WAIT_COLLECT"'>
                <span class="button" @click='show_confirm_complete = true'>收到还款，完结借条</span>
            </footer>
            <footer class="single-button" v-if='(detail.iAmBorrower || detail.iAmlender) && detail.receiptState == "REPAID"'>
                <span class="button transparent" @click='show_confirm_delete = true'>删除借条</span>
            </footer>
        </template>

        <login
            :show='showLogin'
            action='back'
            @finish='getDetail'
            @close='showLogin = false'></login>

        <pay-password
            v-if='userInfo.user'
            :show='showPayPassword'
            @close='showPayPassword=false'
            @finish='payFinish'></pay-password>

        <confirm 
            :show='show_confirm_complete'
            @close='show_confirm_complete = false'
            @confirm='setCompleteIOU'
            title='确认收到还款'
            tips='请确认已收到还款，如未收到还款，切勿点击完成借条，谨防诈骗。'></confirm>

        <confirm 
            :show='show_confirm_delete'
            @close='show_confirm_delete = false'
            @confirm='deleteIOU'
            title='确认删除借条'
            tips='借条删除后，相关记录一并清除，借条不会生效，是否确认删除？'></confirm>

        <confirm 
            :show='show_confirm_return'
            @close='show_confirm_return = false'
            @confirm='returnIOU'
            title='确认退回借条'
            tips='是否确认退回借条'></confirm>

        <sms-code
            v-if='userInfo.user'
            :show='showSmsCode'
            :mobile='userInfo.user.mobile'
            @close='showSmsCode=false'
            @finish='smsFinish'></sms-code>

        <agreement
            :show='showAgreement'
            :iou='iouNo'
            @close='showAgreement=false'></agreement>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import confirm from '../components/Confirm.vue'
    import countDown from '../components/CountDown.vue'
    import smsCode from '../components/SmsCode.vue'
    import agreement from '../components/Agreement.vue'
    import toYuan from '../filters/filter-toYuan'
    import authStep from '../components/AuthStep.vue'
    import dateFormat from '../filters/filter-dateFormat'
    import payPassword from '../components/PayPassword.vue'
    import login from '../components/Login.vue'
    import booleanToStr from '../filters/filter-booleanToStr'
    import { timeToHours } from '../filters/filter-timeFormat'
    import  { mapGetters, mapActions }  from 'vuex'
    import { receiptApi, loanInApi, loanOutApi, contactApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            confirm,
            countDown,
            agreement,
            login,
            smsCode,
            authStep,
            payPassword
        },
        filters:{
            toYuan,
            dateFormat,
            booleanToStr,
            timeToHours
        },
        data() {
            return {
                type:this.$route.query.type,
                placeholderImg:require('../images/loading_1.png'),
                placeholder:'--',
                showTips:false,
                action:'',
                smsCode:'',
                showLogin:false,
                showAgreement:false,
                pageLoaded:false,
                show_confirm_return:false,
                show_confirm_complete:false,
                show_confirm_delete:false,
                number:this.$route.params.number,
                show_modal_close_apply:false,
                detail:{},
                showPayPassword:false,
                showSmsCode:false,
                password:'',
                show_modal_loan_detail:false,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            iouNo(){
                if(!_.isEmpty(this.detail)){
                    if(this.detail.receiptState != 'WAIT_CONFIRM' && this.detail.receiptState != 'RETURNED' ){
                        return this.detail.receiptNo
                    }
                }
            },
            userInfo(){
                return this.localInfo.userInfo
            },
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
            noAuth(){
                if(!this.userInfo.user) return false
                return this.userInfo.user.validState != 'OK'
            },
            days(){

            },
            hasUserCount(){
                return !_.isEmpty(this.userCount)
            },
            noEditObject(){
                return _.isEmpty(this.editObject)
            },
            noInvoiceInfo(){
                return _.isEmpty(this.invoiceInfo)
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setShare',
                'showShare',
                'setMsgTip'
            ]),

            
            daysTransform(from,to,type){
                let suffix
                let fromStr = from
                let toStr = to

                if(type == 'day') suffix = '天'
                else suffix = '期'

                if(from >= 30 && type == 'day'){
                    suffix = '个月'
                    fromStr = from / 30 
                    toStr = to / 30 

                }
                if(from == to){
                    return fromStr + suffix
                }
                else{
                    return fromStr + suffix + '~' + toStr + suffix
                }
            },
            share(item){
                let realUrl = location.href + '?type=share'
                console.log(realUrl)
                // console.log(`金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.repayTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`)
                this.setShare({
                    message:{
                        title: '您有借条待确认，请认真核对信息', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.borrowTime)}- ${dateFormat(item.repayTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () { 

                        },
                        cancel: function () { 

                        }
                    },
                    timeline:{
                        title: '您有一张借条', // 分享标题
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                    qq:{
                        title: '您有一张借条', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.repayTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                })
            },
            setDeleteIOU(){
                this.show_confirm_delete = false
                this.showSmsCode = true
                this.action = 'deleteIOU'
            },
            setAgreeIOU(){
                // if(_.isEmpty(this.userInfo.bankcard)){
                //     this.setMsgTip({
                //         text:'请先绑定银行卡',
                //         type:'warn',
                //     })
                //     this.$router.push({
                //         name:'user-bind-card-verified'
                //     })
                //     return false
                // }

                this.showSmsCode = true
                this.action = 'agreeIOU'
            },
            setCompleteIOU(){
                this.show_confirm_complete = false
                this.showSmsCode = true
                this.action = 'completeIOU'
            },
            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            addContact(result){
                let type = this.$route.query.type
                if(type == 'add'){
                    contactApi.add({
                        mobile:this.userInfo.user.mobile
                    },'share')
                    .then(result=>{
                    })
                    .catch(error => {
                        console.error(error)
                    })
                }
            },
            apply(){
                this.addContact()
                this.$router.push({
                    name:'loan-in-want-index',
                    params:{
                        number:this.number
                    }
                })
            },
            close(){
                loanOutApi.detailOther({
                    lendNo:this.number
                })
                .then(result=>{
                    this.detail = result
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                });
            },
            payFinish(password){
                this.password = password
                this.showPayPassword = false
                if(this.action == 'deleteIOU') this.deleteIOU()
                if(this.action == 'agreeIOU') this.agreeIOU()
                if(this.action == 'completeIOU') {
                    this.showSmsCode = true
                }
            },
            smsFinish(smsCode){
                this.smsCode = smsCode
                this.showSmsCode = false
                if(this.action == 'deleteIOU') this.deleteIOU()
                if(this.action == 'agreeIOU') this.agreeIOU()
                if(this.action == 'completeIOU') {
                    this.completeIOU()
                }
            },
            deleteIOU(){
                this.show_confirm_delete = false
                this.showLoading()
                receiptApi.delete({
                    receiptNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    this.setMsgTip({
                        text:'删除借条成功',
                        type:'success'
                    })
                    this.goRouter('user-index')
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                });
            },
            agreeIOU(){
                this.showLoading()
                receiptApi.agree({
                    receiptNo:this.number,
                    tradePassword:this.password
                })
                .then(result=>{
                    this.hideLoading()
                    this.setMsgTip({
                        text:'同意借条成功',
                        type:'success'
                    })
                    this.getDetail()
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                });
            },
            completeIOU(){
                this.showLoading()
                receiptApi.complete({
                    receiptNo:this.number,
                    tradePassword:this.password,
                    smsCode:this.smsCode
                })
                .then(result=>{
                    this.hideLoading()
                    this.setMsgTip({
                        text:'完成借条成功',
                        type:'success'
                    })
                    this.getDetail()
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                });
            },
            returnIOU(){
                this.show_confirm_return = false
                this.showLoading()
                receiptApi.return({
                    receiptNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    this.setMsgTip({
                        text:'退回借条成功',
                        type:'success'
                    })
                    this.goRouter('user-index')
                })
                .catch(error=> {
                    console.log(error);
                    this.hideLoading()
                });
            },
            passPersent(pass,reject){
                if(pass == 0) return 0
                return pass/(pass+reject)*100
            },
            goRepayment(){
                this.$router.push({
                    name:'loan-in-repayment'
                })
            },
            goSuccess(){
                this.$router.push({
                    name:'loan-in-success'
                })
            },
            test(){
                console.log(1)
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goDetail(item){
                this.$router.push({
                    name:'user-detail',
                    params:{
                        id:item.userId,
                    }
                })
            },
            getDetail(){
                return receiptApi.detail({
                    receiptNo:this.number
                })
                .then(result=>{
                    this.detail = result
                    this.share(result)
                    this.pageLoaded = true
                    this.hideLoading()
                })
                .catch(error=> {
                    console.error(error);
                    this.pageLoaded = true
                    this.hideLoading()
                });
            },
        },
        created(){
            this.showLoading()
            this.getDetail()
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-iou-detail{
        .wrapper{
            padding-bottom: 100px;
        }
        .iou-detail-people{
            display: flex;
            border-bottom: 1px solid $sectionColor;
        }
        .iou-detail-people__item{
            width: 20%;
            flex:1;
            padding:12px 0 16px 0;
            @extend %font-caption;
            span{
                display: inline-block;
                @extend %font-body1;
                color:$importColor;
            }
        }
        .loan-detail-money__list{
            padding:17px 0;
        }
        .loan-detail-main{
            background-color: #fff;
            padding:0 24px;
            padding-bottom: 10px;
            position: relative;
        }
        .loan-detail-info{
            padding-bottom: 0;
        }
        .detail-other-recent{
            padding: 16px 0;
            margin-top: 16px;
            border-top: 1px solid $sectionColor;
            @extend %font-caption;
            p{
                padding-bottom: 8px;
                span{
                    color:$orange;
                }
            }
        }
        .countdown{
            display: flex;
            justify-content: center;
            padding:15px 0;
            @extend %font-body1;
            span{
                display: block;
            }
        }
        .component-count-down{
            color:$red;
        }
    }

</style>
